package com.luatos.iot.regproxy.module;

import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.lang.util.Regex;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.AddDevice;
import com.huaweicloud.sdk.iotda.v5.model.AddDeviceRequest;
import com.huaweicloud.sdk.iotda.v5.model.AddDeviceResponse;
import com.huaweicloud.sdk.iotda.v5.model.ListDevicesRequest;
import com.huaweicloud.sdk.iotda.v5.model.ListDevicesResponse;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceResponse;
import com.huaweicloud.sdk.iotda.v5.region.IoTDARegion;
import com.luatos.iot.regproxy.bean.HuaweicloudProduct;

@At("/reg")
@Fail("http:500")
@IocBean(create = "init")
public class HuaweicloudRegModule {

	private static Log log = Logs.get();

	@Inject
	protected PropertiesProxy conf;

	public void init() {
	}

	@At({"/iotda", "/huaweicloud"})
	@Ok("json:tidy")
	public NutMap huaweicloud(String dev, String key, String sign, String ranstr) {
		NutMap re = new NutMap();
		// 首先, 检查必要的参数
		if (Strings.isBlank(dev) || Strings.isBlank(key)) {
			log.debug("miss dev/key/sign/ranstr");
			return new NutMap("msg", "miss dev/key/sign");
		}
		if (!Regex.match("^[a-zA-z0-9]{10,40}", dev)) {
			log.info("非法的设备名称" + dev);
			return new NutMap("msg", "bad dev name");
		}

		// 基本配置
		HuaweicloudProduct pd = conf.make(HuaweicloudProduct.class, "luatos.regproxy.huaweicloud." + key + ".");

		ICredential auth = new BasicCredentials().withAk(pd.ak).withSk(pd.sk);

		IoTDAClient client = IoTDAClient.newBuilder().withCredential(auth).withRegion(IoTDARegion.valueOf(pd.region))
				.build();

		String devid = key + "_" + dev;
		re.put("devid", devid);
		re.put("region", pd.region);
		log.debug("devid " + devid);

		// 先查询整体查询
		ListDevicesRequest req_list = new ListDevicesRequest();
		req_list.withNodeId(dev);
		req_list.withProductId(key);
		
		ListDevicesResponse resp_list = client.listDevices(req_list);
		if (resp_list.getPage() != null && resp_list.getPage().getCount() > 0) {
			ShowDeviceRequest req_show = new ShowDeviceRequest();
			try {
				req_show.withDeviceId(devid);
				ShowDeviceResponse response = client.showDevice(req_show);
				if (response.getAuthInfo() != null) {
					re.put("secret", response.getAuthInfo().getSecret());
					return re;
				}
			} catch (Exception e) {
				log.info("show device error", e);
			}
		}

		// 注册新设备
		AddDeviceRequest req_add = new AddDeviceRequest();
		try {
			AddDevice ad = new AddDevice();
			ad.withNodeId(dev);
			ad.withProductId(key);
			req_add.withBody(ad);
			AddDeviceResponse resp2 = client.addDevice(req_add);
			if (resp2.getAuthInfo() != null) {
				re.put("secret", resp2.getAuthInfo().getSecret());
				return re;
			}
		} catch (Exception e) {
			log.info("add device error", e);
		}
		re.setv("err", "server error");
		return re;
	}
}
